package com.d3works.apps.contract.web;

import com.d3works.apps.base.callable.ControllerCallableTool;
import com.d3works.apps.base.db.Batch;
import com.d3works.apps.contract.batch.service.BatchContractService;
import com.d3works.apps.contract.db.ContractBatch;
import com.d3works.apps.contract.db.repo.ContractBatchRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;

@Singleton
public class ContractBatchController {

  public void runBatch(ActionRequest request, ActionResponse response) {
    try {
      ContractBatch contractBatch = request.getContext().asType(ContractBatch.class);
      contractBatch = Beans.get(ContractBatchRepository.class).find(contractBatch.getId());
      BatchContractService batchContractService = Beans.get(BatchContractService.class);
      batchContractService.setBatchModel(contractBatch);
      ControllerCallableTool<Batch> controllerCallableTool = new ControllerCallableTool<>();
      Batch batch = controllerCallableTool.runInSeparateThread(batchContractService, response);
      if (batch != null) {
        response.setInfo(batch.getComments());
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    } finally {
      response.setReload(true);
    }
  }
}
